package com.zzyk.microCloud.api.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.mapper.TestConnectionMapper;
import com.zzyk.main.model.pojo.*;
import com.zzyk.main.model.vo.*;
import com.zzyk.main.mqtt.MyMqttClient;
import com.zzyk.main.service.*;
import com.zzyk.main.utils.HttpUtils;
import com.zzyk.main.utils.RedisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.*;

@RestController
@RequestMapping("/api/deviceData")
@Log4j2
public class ApiDeviceController extends ApiBaseController {

    /**
     * MQTT服务器地址
     */
    @Value("${mqtt.host}")
    private String host;
    /**
     * MQTT服务器认证用户名
     */
    @Value("${mqtt.username}")
    private String username;
    /**
     * MQTT服务器认证密码
     */
    @Value("${mqtt.password}")
    private String password;
    /**
     * MQTT通信使用字符编码
     */
    @Value("${mqtt.charset}")
    private String charset;
    @Resource
    private MyMqttClient mqttConnect;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceUserateService deviceUserateService;
    @Autowired
    private DeviceElectricityDayService electricityDayService;
    @Autowired
    private ISysOrganizationService sysOrganizationService;
    @Resource
    private VwDeviceProduceService deviceProduceService;
    @Autowired
    private DeviceParamService deviceParamService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private DeviceHarmonicRealService deviceHarmonicRealService;





    /**
     * 设备每日平均生产时长走势
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/getAvgProductionTime")
    public List<CommonKeyValue> getAvgProductionTime(String dateTime) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getAvgProductionTime(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取设备类型稼动率
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/getDeviceTypeUtilizationRate")
    public List<KeyValueTwo> getDeviceTypeUtilizationRate(String dateTime) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceUserateService.getDeviceTypeUtilizationRate(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取 生产详情
     *
     * @return
     */
    @GetMapping("/ProductionDetails")
    public Message getProductionDetails(String dateTime) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        setPage();
        PageInfo<ProductionDetails> info = new PageInfo<>(deviceService.getProductionDetails(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList()));
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }
    /**
     * 获取生产报告下数据
     *
     * @param dateTime
     * @return
     * @throws UserException
     */
    @GetMapping("/productionReport")
    public List<DeviceUserate> getProductionReport(String dateTime) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceUserateService.getProductionReport(dateTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 根据条件获取生产时长
     *
     * @param time 时间
     * @return
     */
    @GetMapping("/getProductionTimeHistogram")
    public List<KeyValue> getProductionTimeHistogram(String time) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findProductionTimeHistogram(sysUser.getEnterprise(), time, sysUser.getDeviceList());
    }

    /**
     * 获取今日用电量 柱状图
     *
     * @param day
     * @return
     */
    @GetMapping("/getEnergyUsedByDay")
    public List<Map<String, Object>> getEnergyUsedByDay(@RequestParam("day") String day) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getEnergyUsedByDay(day, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取单日用电量 的峰谷平电量电费总电量电费
     *
     * @param day
     * @return
     * @throws UserException
     */
    @GetMapping("/getMorePowerConsumptionDay")
    public DeviceElectricityDay getMorePowerConsumptionDay(@RequestParam("day") String day) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getMorePowerConsumptionDay(day, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取某年每个月的能耗
     *
     * @param year
     * @return
     * @throws UserException
     */
    @GetMapping("/getMorePowerConsumptionYear")
    public List<Map<String, Object>> getMorePowerConsumptionYear(String year) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getMorePowerConsumptionYear(year, sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取大屏首页用电量更多数据
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/getMorePowerConsumption")
    public List<Map<String, Object>> getMorePowerConsumption(String startTime, String endTime) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getMorePowerConsumption(startTime, endTime, sysUser.getEnterprise(), sysUser.getDeviceList());
    }


    /**
     * 获取登录用户所辖企业下  稼动率
     *
     * @return
     */
    @GetMapping("/getUsageRateTwo")
    public Message getUsageRateTwo(String dateTime, String deviceName, Integer deviceType) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        setPage();
        PageInfo<KeyValueTwo> info = new PageInfo<>(deviceService.findUsageRateTwo(sysUser.getEnterprise(), dateTime, deviceName, deviceType, sysUser.getDeviceList()));
        return Message.success()
                .addData("data", info.getList())
                .addData("total", info.getTotal())
                .addData("pages", info.getPages());
    }

    /**
     * 获取首页今日用能 根据设备类型分组
     *
     * @return
     * @throws UserException
     */
    @GetMapping("/getTheEnergyYouUseToday")
    public List<KeyValue> getTheEnergyYouUseToday() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.getTheEnergyYouUseToday(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    @GetMapping("/getDeviceProduceByEnterpise")
    public Message getDeviceProduceByEnterpise() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return Message.success().addData("data", deviceProduceService.list(new LambdaQueryWrapper<VwDeviceProduce>().eq(VwDeviceProduce::getEnterpise, sysUser.getEnterprise()).isNotNull(VwDeviceProduce::getDeviceType)));
    }

    /**
     * 根据 clientID 获取设备参数
     *
     * @param clientID
     * @return
     */
    @GetMapping("/getDeviceParamByClientID")
    public DeviceParam getDeviceParamByClientID(String clientID) {
        return deviceParamService.selectOneByDeviceId(clientID);
    }

    /**
     * 根据设备编号查询设备信息
     *
     * @param sn   设备编号
     * @param type 设备类型 0采集设备 1生产设备
     * @return
     */
    @GetMapping("/getDeviceBySn")
    public Device getDeviceBySn(String sn, Integer type) throws UserException {
        Device device = deviceService.findDeviceBySnAndType(sn, type);
        SysUser sysUser = getUser().getSysUser();
        if (ObjectUtil.isNotNull(device) && device.getEnterpise().equals(sysUser.getEnterprise())) {
            return device;
        }
        return null;
    }

    /**
     * 验证编号是否存在
     *
     * @param sn
     * @return
     */
    @GetMapping("/getOneBySn")
    public Boolean getOneBySn(String sn) {
        Device device = deviceService.selectDeviceByNumber(sn, 1);
        return ObjectUtil.isNull(device) ? true : false;
    }

    /**
     * 小程序添加生产设备接口
     *
     * @param device
     * @return
     */
    @PostMapping("/saveDevice")
    @Transactional
    public Message saveDevice(Device device) {
        log.debug("小程序添加设备参数{}", device);
        try {
            Device device1 = deviceService.selectByClientId(device.getClientId());
            device.setGroup(device1.getId());
            device.setType(1);
            device.setClientId(null);
            deviceService.addProductionEquipment(device);
            device1.setEnterpise(device.getEnterpise());
            deviceService.updateByPrimaryKeySelective(device1);
            return Message.success();
        } catch (Exception e) {
            log.debug("小程序添加设备异常信息{}", e.getMessage());
            e.printStackTrace();
            return Message.failed("添加失败");
        }
    }

    /**
     * 根据clientID生产设备名称 编号 所属公司
     *
     * @param clientId
     * @return
     */
    @GetMapping("/productionEquipmentInformation")
    public Message productionEquipmentInformation(String clientId) throws UserException {
        SysUser user = getUser().getSysUser();
        String substring = clientId.substring(clientId.indexOf("/") + 1, clientId.indexOf("/") + 2);
        String dName = "1".equals(substring) ? "2 MTDC-380L-01" : "4 MTDC-380F-01";
        String[] split = clientId.split("/");
        String number = split[3];
        List<Organization> list = sysOrganizationService.getList(user.getArea());
        return Message.success().addData("dName", dName).addData("number", number).addData("Organization", list);
    }

    /**
     * 根据clientID获取生产设备信息
     *
     * @param clientId
     * @return
     */
    @GetMapping("/getDeviceDateByClientId")
    public Message getDeviceDateByClientId(String clientId) {
        Device device = deviceService.selectProductionDeviceByClientId(clientId);
        return Message.success().addData("data", device);
    }

    /**
     * 测试链接采集设备
     *
     * @param clientId
     * @return
     */
    @GetMapping("/connectionDevice")
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Message connectionDevice(String clientId) throws UserException, MqttException, InterruptedException {
        clientId = clientId.trim();
        SysUser user = getUser().getSysUser();
        if (StringUtils.isBlank(clientId)) {
            throw new UserException("clientId有误");
        }
        String Topid = clientId.substring(0, clientId.length() - 2);
        Device device = new Device();
        device.setType(0);
        device.setEnterpise(user.getEnterprise());
        try {
            String substring = clientId.substring(clientId.indexOf("/") + 1, clientId.indexOf("/") + 2);
            MqttMessage message = new MqttMessage();
            message.setClient(clientId);
            message.setQos(0);
            message.setRetain(false);
            message.setTopic(Topid + "tx");
            if ("4".equals(substring)) {
                device.setName("4 MTDC-380F-01");
                message.setPayload("{\"Print_Config\":1}");
            } else {
                device.setName("2 MTDC-380L-01");
                message.setPayload("{\"confirmed\":true,\"data\":\"eyJQcmludF9Db25maWciOjF9\",\"fPort\":10}");
            }
            String[] split = clientId.split("/");
            String number = split[3];
            device.setSn(number);
            device.setClientId(clientId);
            MqttReturn mqttReturn = sendCommand(message);
            if (mqttReturn.getCode() != 0) {
                return Message.failed("连接失败，错误代码：" + mqttReturn.getCode());
            }
            mqttConnect.start(clientId);
            Thread.sleep(1000);
            String conf = (String) redisUtils.get(clientId + "_conf");
            int time = 1000;
            while (StringUtils.isBlank(conf)) {
                Thread.sleep(1000);
                conf = (String) redisUtils.get(clientId + "_conf");
                time += 1000;
                if (time == 1000 * 59) {
                    log.debug("测试连接超过一分钟,clientId：{}", clientId);
                    return Message.failed("连接失败");
                }
            }
            if (StringUtils.isNotBlank(conf)) {
                deviceService.insertSelective(device);
            }
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed();
        } finally {
            log.debug("关闭mqtt连接");
            mqttConnect.close();
        }
    }

    /**
     * 激活采集 程序入口
     *
     * @return 0 未激活  1 已经激活，未绑定设备 2 无权限  3设备已激活已绑定并且有权限
     */
    @GetMapping("/activateTheCollectionPortal")
    public Map<String, Object> activateTheCollectionPortal(String id) throws UserException {
        SysUser user = getUser().getSysUser();
        Map<String, Object> map = new HashMap(1);
        if (ObjectUtil.isNull(user)) {
            map.put("status", 2);
            return map;
        }
        Device device = deviceService.selectByClientId(id);
        if (ObjectUtil.isNull(device)) {
            map.put("status", 0);
            return map;
        } else {
            Device device1 = deviceService.selectdeviceByGroup(device.getId());
            if (ObjectUtil.isNull(device1)) {
                map.put("status", 1);
                map.put("date", device.getCreateTime());
                return map;
            } else {
                List<String> areas = Arrays.asList(user.getArea());
                if (areas.contains(device.getEnterpise().toString())) {
                    map.put("status", 3);
                    return map;
                } else {
                    map.put("status", 2);
                    return map;
                }
            }
        }

    }

    /**
     * 获取报告管理下的结论
     *
     * @param month
     * @return
     * @throws UserException
     */
    @GetMapping("/getReportConclusion")
    public Map<String, Object> getReportConclusion(String month) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findReportConclusion(sysUser.getEnterprise(), month, sysUser.getDeviceList());
    }

    /**
     * 用能总览概括
     *
     * @param month
     * @return
     * @throws UserException
     */
    @GetMapping("/getOverviewOfEnergyUse")
    public HashMap<String, DeviceElectricityDay> getOverviewOfEnergyUse(String month) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return electricityDayService.findOverviewOfEnergyUse(sysUser.getEnterprise(), month, sysUser.getDeviceList());
    }

    /**
     * 报告管理下用电质量参数考核分析 按月份查询
     *
     * @param month 月 默认为本月
     * @return
     */
    @GetMapping("/getElectricityParameters")
    public List<DeviceExtraData> getElectricityParameters(String month) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findElectricityParameters(sysUser.getEnterprise(), month, sysUser.getDeviceList());
    }

    /**
     * 获取用电统计下所需数据
     *
     * @return
     */
    @GetMapping("/getElectricityStatistics")
    public CommonTimePojo getElectricityStatistics() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findElectricityStatistics(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取企业所辖设备的有功和额定功率
     *
     * @return
     */
    @GetMapping("/getEnterprisePowerData")
    public List<KeyValue> getEnterprisePowerData() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findEnterprisePowerData(sysUser.getEnterprise());
    }

    /**
     * 获取更多生产时长 首页生产时长用
     */
    @GetMapping("/getMoreProductionTime")
    public EnterpriseProductionTime getMoreProductionTime() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findMoreProductionTime(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取企业所辖所有设备的原始数据
     *
     * @return
     */
    @GetMapping("/getEnterpriseDeviceOriginData")
    public List<DeviceOriginData> getEnterpriseDeviceOriginData() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findEnterpriseDeviceOriginData(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取企业用电分析下的健康指数评分
     *
     * @return
     */
    @GetMapping("/getEnterpriseHealth")
    public String getEnterpriseHealth() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        List<DeviceExtraData> enterpriseExtraData = deviceService.findEnterpriseExtraData(sysUser.getEnterprise(), sysUser.getDeviceList());
        Double pf = 0.0;
        for (DeviceExtraData enterpriseExtraDatum : enterpriseExtraData) {
            pf += Double.parseDouble(enterpriseExtraDatum.getHealth());
        }

        return String.format("%.1f", pf / enterpriseExtraData.size());
    }

    /**
     * 获取企业所辖所有设备实时数据
     *
     * @return
     */
    @GetMapping("/getEnterpriseExtraData")
    public List<DeviceExtraData> getEnterpriseExtraData() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findEnterpriseExtraData(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取登录用户所辖企业下所有设备功率总和
     *
     * @return
     */
    @GetMapping("/getEnterprisePower")
    public List<DateAndString> getEnterprisePower() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findEnterprisePower(sysUser.getEnterprise());
    }


    /**
     * 获取登录用户所辖企业下 所有设备使用率
     *
     * @return
     */
    @GetMapping("/getUsageRate")
    public List<Map<String, Object>> getUsageRate() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findUsageRate(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取本企业下所有设备今日用电量
     *
     * @return
     */
    @GetMapping("/getToDayPower")
    public List<DateAndString> getToDayPower() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findToDayPower(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取生产时长区域下所需的数据
     *
     * @return
     * @throws UserException
     */
    @GetMapping("/getToDayProductionTime")
    public String getTotalProductionTime() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findToDayProductionTime(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取设备使用率
     *
     * @return
     */
    @GetMapping("/getDeviceUserate")
    public List<DeviceUserate> getDeviceUserate(Integer id, String beginTime, String endTime, Integer type) {
        return deviceUserateService.findDeviceUserateBuDeviceId(id, beginTime, endTime, type);
    }


    /**
     * 根据企业ID获取生产设备
     *
     * @return
     */
    @GetMapping("/getDeviceByEId")
    public List<Device> getDeviceByEId() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findDeviceByEId(sysUser.getEnterprise(), sysUser.getDeviceList());
    }

    /**
     * 获取用电分析数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getPowerConsumptionStatistics")
    public PowerConsumptionStatistics getPowerConsumptionStatistics(@RequestParam("id") Integer id) {
        return deviceService.findPowerConsumptionStatistics(id);
    }


    /**
     * 获取当天生产时长
     *
     * @param id
     * @return
     */
    @GetMapping("/getTodayDeviceProductionTime")
    public String getTodayProductionTime(Integer id) {
        return deviceService.findTodayProductionTime(id);
    }

    /**
     * 获取本月生产时长
     *
     * @param id
     * @return
     */
    @GetMapping("/getProductionTime")
    public List<DateAndString> getProductionTime(Integer id, String beginTime, String endTime, Integer type) {
        return deviceService.findProductionTime(id, beginTime, endTime, type);
    }

    /**
     * 根据时间范围查询功率
     *
     * @param id
     * @return
     */
    @GetMapping("/getRealPowerParam")
    public List<DateAndString> getRealPowerParam(Integer id, String beginTime, String endTime, Integer type) {
        return deviceService.findRealPowerParam(id, beginTime, endTime, type);
    }

    /**
     * 根据ID查询 实时功率 当天
     *
     * @param id
     * @return
     */
    @GetMapping("/getRealPower")
    public List<DateAndString> getRealPower(Integer id) {

        return deviceService.findRealPower(id);
    }

    /**
     * 根据用户传入的时间范围查询用电量、默认查询一个月。
     *
     * @param id
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/getTodayElectricityByParam")
    public List<DateAndString> getTodayElectricityByParam(Integer id, String beginTime, String endTime) {
        return deviceService.findTodayElectricityByParam(id, beginTime, endTime);
    }

    /**
     * 获取今天用电量
     *
     * @param id
     * @return
     */
    @GetMapping("/getTodayElectricity")
    public List<DateAndString> getTodayElectricity(Integer id) {
        return deviceService.findTodayElectricity(id);
    }

    /**
     * 用电分析更多图表
     *
     * @param id
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/getElectricityAnalysisDataByParam")
    public List<DeviceExtraData> getElectricityAnalysisDataByParam(Integer id, String beginTime, String endTime) {
        return deviceService.findElectricityAnalysisDataByParam(id, beginTime, endTime);
    }

    /**
     * 根据设备ID去查询设备实时数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getElectricityAnalysisData")
    public DeviceExtraData getElectricityAnalysisData(Integer id) {
        return deviceService.findElectricityAnalysisData(id);
    }

    /**
     * 根据采集设备ID获取采集设备信息
     *
     * @return
     */
    @GetMapping("/getDeviceByGroup")
    public Device getDeviceByGroup(Integer group) {
        return deviceService.selectByPrimaryKey(group);
    }


    /**
     * 添加采集设备信息
     *
     * @param device
     * @return
     */
    @PostMapping("/saveCollectionEquipment")
    public Message saveCollectionEquipment(Device device) {
        try {
            device.setType(0);
            deviceService.insertSelective(device);
            return Message.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.failed("保存失败");
        }
    }

    /**
     * 统计生产设备设备全部数量和各个状态的数量
     *
     * @return
     */
    @GetMapping("getDeviceTotalByCompany")
    public Result getDeviceTotalByCompany() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        try {
            return Result.ok(deviceService.getTotal(1, sysUser.getEnterprise(), null, sysUser.getDeviceList()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 根据设备编号去查询 设备信息
     *
     * @param sn
     * @return 如果编号已经有了那么就返回true反之为false
     */
    @PostMapping("/verificationDeviceByNumber")
    public Map<String, Boolean> verificationDeviceByNumber(String sn, Integer type) {
        Map<String, Boolean> map = new HashMap<>(8);
        Device device = deviceService.selectDeviceByNumber(sn, type);
        if (ObjectUtil.isNull(device)) {
            map.put("valid", false);
            return map;
        }
        map.put("valid", true);
        return map;

    }

    /**
     * 获取设备列表数据
     *
     * @param param
     * @return
     */
    @GetMapping("/getDeviceList")
    public List<DeviceRealData> getDeviceList(String param) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.apiGetDeviceListDataTo(sysUser.getEnterprise(), param, sysUser.getDeviceList());
    }


    /**
     * 获取设备列表数据
     *
     * @param param
     * @return
     */
    @GetMapping("/getDeviceListTo")
    public Message getDeviceListTo(String param, Integer pageIndex, Integer pageSize) throws UserException {
        SysUser sysUser = getUser().getSysUser();

        return deviceService.getDeviceListData(sysUser.getEnterprise(), param, 0, "time", pageIndex, pageSize, null, sysUser.getDeviceList());
    }

    /**
     * 时间稼动率
     *
     * @return
     * @throws UserException
     */
    @GetMapping("/getUsageRateTwoApi")
    public List<KeyValueTwo> getUsageRateTwo() throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.findUsageRateTwo(sysUser.getEnterprise(), "", "", 0, sysUser.getDeviceList());
    }

    /**
     * 根据ID查询设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getProduceDeviceById")
    public Result getProduceDeviceById(Integer id) {
        try {
            return Result.ok(deviceService.selectDeviceById(id, 1));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 获取生产设备归管理设备列表
     *
     * @param param 快捷查询参数
     * @return
     */
    @GetMapping("getDeviceListByEnterprise")
    public List<Device> getDeviceListByEnterprise(String param) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return deviceService.selectAllByParam(param, 1, sysUser.getEnterprise(), null, sysUser.getDeviceList(), null);
    }

    /**
     * 根据设备ID获取设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getDeviceByDid")
    public Device getDeviceByDid(Integer id) {
        return deviceService.selectByPrimaryKey(id);
    }

    /**
     * 生成二维码
     *
     * @return 二维码本地地址
     */
    @GetMapping(value = "/getCloudQrCode", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getCloudQrCode(String value) {
        return QrCodeUtil.generatePng(value, 100, 100);
    }

    /**
     * 发送mqtt命令
     *
     * @param message
     * @return
     * @throws UnsupportedEncodingException
     * @throws MalformedURLException
     */
    private MqttReturn sendCommand(MqttMessage message) throws UnsupportedEncodingException, MalformedURLException {
        String auth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(charset));
        String doPost = HttpUtils.doPost(host, JSON.toJSONString(message), auth, Charset.forName(charset));
        System.out.println("doPost = " + doPost);
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(doPost);
        return JSONUtil.toBean(jsonObject, MqttReturn.class);
    }

    /**
     * 获取年稼动率数据
     *
     * @param year
     * @return
     */
    @GetMapping("/getAnnualUtilizationRate")
    public Message getAnnualUtilizationRate(String year) throws UserException {
        SysUser sysUser = getUser().getSysUser();
        return Message.success()
                .addData("data", deviceUserateService.getAnnualUtilizationRate(year, sysUser.getEnterprise(), sysUser.getDeviceList()))
                .addData("type", deviceService.countDeviceType(sysUser.getEnterprise(), sysUser.getDeviceList()));
    }

    /**
     * 获取最新的谐波实时表
     */
    @GetMapping("/getDeviceHarmonicReal")
    public Message getDeviceHarmonicReal(Integer deviceId) {
        return Message.success().addData("data", deviceHarmonicRealService.getOne(new LambdaQueryWrapper<DeviceHarmonicReal>().eq(DeviceHarmonicReal::getDeviceId, deviceId).last("limit 1")));
    }


}

